﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using System.Threading;

namespace StuMana.Services
{
    public class COM
    {
        //Cong COM.
        public SerialPort serialPort;
        //buffer chua cac data nhan duoc tu cong COM.
        private byte[] serial_buffer = new byte[1000];
        private byte[] serial_get = new byte[30];

        //Mảng bytes vừa nhận được.
        private Boolean onReceived=false;
        
        // Hết thời gian kết nối
        private Boolean timeSession;

        // Timer dem time cho
        private System.Windows.Forms.Timer readTimer;

        //Xac dinh xem da connect voi cong COM chưa?
        public Boolean isConnected = false;

        // moi lan nhan data chi co the nhan dc 8 byte -> dem so byte can nhan
        // de ghep voi cac bytes array cho du so luong bytes
        //dem so bytes hien co trong buffer .
        private int cnt_seria = 0;
        private int counter = 0;
        public COM()
        { }
        public COM(string portName,int baud)
        {
            //timer setting
            readTimer = new System.Windows.Forms.Timer();
            readTimer.Interval = 100;
            readTimer.Tick += new EventHandler(readTimer_Tick);

            try
            {
                serialPort = new SerialPort();
                serialPort.PortName = portName;
                serialPort.BaudRate = baud;
                serialPort.DataBits = 8;
                serialPort.Parity = Parity.None;
                serialPort.StopBits = StopBits.One;
                serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
                serialPort.ReadBufferSize = 1024;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        public SerialPort connecting()
        {
            serialPort.Open();
            isConnected = true;
            //MessageBox.Show("Ket noi COM thanh cong");
            return serialPort;
        }

        /*
         * Nhan du lieu tu cong COM
         * Day la su kien cua Serial Port
         */
        private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {   
            int intBytes = serialPort.BytesToRead;
            byte[] bytes = new byte[intBytes];
            serialPort.Read(bytes, 0, intBytes);

            for (int cnt = 0; cnt < intBytes; cnt++)
            {
                serial_buffer[cnt_seria] = bytes[cnt];
                cnt_seria++;
            }

            if (serial_buffer[0] == SL025M.Header_rec)
            {
                if ((serial_buffer[1] + 2) == (cnt_seria))
                {
                    byte[] fill_dat = new byte[cnt_seria + 1];
                    for (int i = 0; i < cnt_seria; i++)
                    {
                        fill_dat[i] = serial_buffer[i];
                    }
                    counter = cnt_seria;
                    set_array(fill_dat, cnt_seria, serial_get);
                    cnt_seria = 0;
                }
            }

        }

        /*
         * assign byte array to buff
         */
        public void set_array(byte[] receive,int cnt, byte[] buff)
        {
                for (int i = 0; i < cnt; i++)
                {
                    buff[i] = receive[i];
                }
                onReceived = true;
        }

        /*
         * Timer handling
         */
        private void readTimer_Tick(object sender, EventArgs e)
        {
            timeSession = true;
        }

        /*
         * Get array
         */
        public int getArray(byte[] buff)
        {
            System.DateTime moment= new DateTime();
            moment = DateTime.Now;                
            int timestamp=moment.Second;
            //readTimer.Enabled = true;
            // Doi ket qua tra ve           
            while (onReceived == false)
            {
                moment = DateTime.Now;                
                if (moment.Second>timestamp+1)
                {                 
                    return 5000;
                }    
                else if(moment.Second<timestamp)
                {
                    if (moment.Second + 60 > timestamp + 1)
                        return 5000;
                }
            }

            for (int i = 0; i < counter; i++)
            {
                buff[i] = serial_get[i];
            }
          //  else            
          //  {
           //     return 5000;
          //  }
            
            //  MessageBox.Show("Length: "+counter.ToString());
            readTimer.Enabled = false;
            onReceived = false;
            //readTimer.Enabled = false;
            return counter;           

        }
        // get serial to buffer
        public int getdata(byte[] serial_buff)
        {
            int size = getArray(serial_buff);

            if (size == 5000)
            {
                return 5000;
            }
            return size;
        }

               

        /**
         * Close com port.
         */
        public void closeCOMPort()
        {
            try
            {
                serialPort.Close();
                isConnected = false;
                serialPort = null;
                //instance = null;
            }
            catch(Exception es)
            {
                MessageBox.Show("Khong dong duoc ket noi"+es.Message,"Loi ket noi");
            }
        }

        public SerialPort returnConnect()
        {
            return serialPort;
        }
    }
}